import os
import tempfile
from flask import Flask, render_template, request, redirect, url_for
import requests
import json

# Flask 服务器配置示例
from flask import send_from_directory

app = Flask(__name__, static_folder='static')

# 静态文件路由
@app.route('/static/<path:path>')
def serve_static(path):
    return send_from_directory('static', path)

app.config['UPLOAD_FOLDER'] = tempfile.gettempdir()
app.config['ALLOWED_EXTENSIONS'] = {'txt'}

# DeepSeek API配置（写死）
DEEPSEEK_API_KEY = "sk-gskfqqyvcayxexdtehxwmhjtlkfqqhygoffgunzvpqckdkov"
DEEPSEEK_API_URL = "https://api.siliconflow.cn/v1/chat/completions"

def allowed_file(filename):
    """检查文件扩展名是否允许"""
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']


def analyze_text(content):
    """调用DeepSeek API分析文本"""
    # 构建提示词
    prompt = f"{content}\n\n请帮我查找上面内容的需要修改的地方，分错别字检查、建议修改、标点、敏感词几种类别，帮我生成一个三列，第一列为 类别 第二列为原文，第三列要改为的内容。列和列之间用“|”号分割。"

    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {DEEPSEEK_API_KEY}"
    }

    data = {
        "model": "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B",
        "messages": [
            {"role": "user", "content": prompt}
        ],
        "temperature": 0.1,
        "max_tokens": 2000
    }

    try:
        response = requests.post(DEEPSEEK_API_URL, headers=headers, data=json.dumps(data))
        response.raise_for_status()
        result = response.json()
        return result['choices'][0]['message']['content']
    except Exception as e:
        print(f"API调用错误: {e}")
        return None


def parse_suggestions(api_response):
    """解析API返回的建议"""
    suggestions = []
    print(api_response)
    if not api_response:
        return suggestions
    lines = api_response.strip().split('\n')
    for line in lines:
        print(line)
        # 跳过标题行和分隔行
        if "类别" in line or "---" in line:
            continue
        print("=======真实内容===================")
        print(line)
        parts = line.replace(" ","").split('|')
        print(parts)
        if len(parts) >= 5:
            category = parts[1].strip()
            original = parts[2].strip()
            corrected = parts[3].strip()
            print(category,original,corrected)
            # 检查是否是有效类别
            valid_categories = ["错别字", "建议修改", "标点", "敏感词"]
            if category in valid_categories:
                suggestions.append({
                    "category": category,
                    "original": original,
                    "corrected": corrected,
                    "show": True
                })
    print("==============修改的建议=======================")
    print(suggestions)
    return suggestions


def apply_suggestions(original_content, suggestions):
    """应用建议到原文"""
    modified_content = original_content

    # 按原始文本中的位置排序建议（从后向前，避免索引变化）
    # 注意：这里简化处理，实际应用中应根据文本位置精确排序
    for suggestion in reversed(suggestions):
        if suggestion['show']:
            modified_content = modified_content.replace(
                suggestion['original'],
                suggestion['corrected']
            )

    return modified_content


@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # 检查是否有文件上传
        if 'file' not in request.files:
            return redirect(request.url)

        file = request.files['file']

        # 检查是否选择了文件
        if file.filename == '':
            return redirect(request.url)

        # 检查文件类型
        if file and allowed_file(file.filename):
            # 保存文件到临时位置
            filename = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
            file.save(filename)

            # 读取文件内容
            try:
                with open(filename, 'r', encoding='utf-8') as f:
                    content = f.read()
            except UnicodeDecodeError:
                # 尝试其他编码
                try:
                    with open(filename, 'r', encoding='gbk') as f:
                        content = f.read()
                except:
                    return "无法解析文件编码，请确保文件是UTF-8或GBK编码。"

            # 调用API分析文本
            api_response = analyze_text(content)
            print("=========返回的内容==========")
            print(api_response)

            # 解析建议
            suggestions = parse_suggestions(api_response)

            # 计算各类别的数量
            category_counts = {
                "错别字检查": sum(1 for s in suggestions if s['category'] == "错别字检查" and s['show']),
                "建议修改": sum(1 for s in suggestions if s['category'] == "建议修改" and s['show']),
                "标点": sum(1 for s in suggestions if s['category'] == "标点" and s['show']),
                "敏感词": sum(1 for s in suggestions if s['category'] == "敏感词" and s['show'])
            }

            # 存储会话数据
            session_data = {
                'original_content': content,
                'suggestions': suggestions,
                'category_counts': category_counts
            }

            # 将数据存储到临时文件
            session_filename = os.path.join(app.config['UPLOAD_FOLDER'], f"session_{os.urandom(16).hex()}.json")
            with open(session_filename, 'w', encoding='utf-8') as f:
                json.dump(session_data, f, ensure_ascii=False)

            return redirect(url_for('show_results', session_id=os.path.basename(session_filename)))

    return render_template('index.html')


@app.route('/results/<session_id>', methods=['GET', 'POST'])
def show_results(session_id):
    session_filename = os.path.join(app.config['UPLOAD_FOLDER'], session_id)

    # 检查会话文件是否存在
    if not os.path.exists(session_filename):
        return "会话已过期，请重新上传文件。", 404

    # 读取会话数据
    with open(session_filename, 'r', encoding='utf-8') as f:
        session_data = json.load(f)

    print("====================打印session=======================")
    print(session_data)

    if request.method == 'POST':
        action = request.form.get('action')

        if action == 'ignore':
            # 忽略某个建议
            index = int(request.form.get('index'))
            session_data['suggestions'][index]['show'] = False

            # 更新类别计数
            session_data['category_counts'] = {
                "错别字检查": sum(
                    1 for s in session_data['suggestions'] if s['category'] == "错别字检查" and s['show']),
                "建议修改": sum(1 for s in session_data['suggestions'] if s['category'] == "建议修改" and s['show']),
                "标点": sum(1 for s in session_data['suggestions'] if s['category'] == "标点" and s['show']),
                "敏感词": sum(1 for s in session_data['suggestions'] if s['category'] == "敏感词" and s['show'])
            }

            # 保存更新后的会话数据
            with open(session_filename, 'w', encoding='utf-8') as f:
                json.dump(session_data, f, ensure_ascii=False)

            return redirect(url_for('show_results', session_id=session_id))

        elif action == 'proofread':
            # 应用所有建议
            modified_content = apply_suggestions(
                session_data['original_content'],
                session_data['suggestions']
            )

            # 更新会话数据
            session_data['original_content'] = modified_content

            # 保存更新后的会话数据
            with open(session_filename, 'w', encoding='utf-8') as f:
                json.dump(session_data, f, ensure_ascii=False)

            return redirect(url_for('show_results', session_id=session_id))

    print("============返回页面")
    print(session_data)
    return render_template('results.html', **session_data)


@app.route('/api/proofread', methods=['POST'])
def proofread():
    data = request.json
    content = data.get('text', '')

    # 调用API分析文本
    api_response = analyze_text(content)
    print("=========返回的内容==========")
    print(api_response)

    # 解析建议
    suggestions = parse_suggestions(api_response)

    # 计算各类别的数量
    category_counts = {
        "错别字检查": sum(1 for s in suggestions if s['category'] == "错别字检查" and s['show']),
        "建议修改": sum(1 for s in suggestions if s['category'] == "建议修改" and s['show']),
        "标点": sum(1 for s in suggestions if s['category'] == "标点" and s['show']),
        "敏感词": sum(1 for s in suggestions if s['category'] == "敏感词" and s['show'])
    }

    # 存储会话数据
    session_data = {
        'original_content': content,
        'suggestions': suggestions,
        'category_counts': category_counts
    }

    # 将数据存储到临时文件
    session_filename = os.path.join(app.config['UPLOAD_FOLDER'], f"session_{os.urandom(16).hex()}.json")
    with open(session_filename, 'w', encoding='utf-8') as f:
        json.dump(session_data, f, ensure_ascii=False)
    return json.dumps(session_data)


if __name__ == '__main__':
    app.run(host="0.0.0.0",debug=True)